package com.mec.web.y2012.coreservlet;

import static com.mec.web.y2012.coreservlet.RegistrationFormServlet.EMAIL_ADDRESS;
import static com.mec.web.y2012.coreservlet.RegistrationFormServlet.FIRST_NAME;
import static com.mec.web.y2012.coreservlet.RegistrationFormServlet.LAST_NAME;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mec.beans.y2012.coreservlet.LongLivedCookie;

@WebServlet("/RegistrationServlet")
public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public RegistrationServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		boolean isMissingValue = false;
		
		//
		String firstName = request.getParameter(FIRST_NAME);
		if(isMissing(firstName)){
			firstName  = "Missing first Name";
			isMissingValue = true;
		}
		
		//
		String lastName = request.getParameter(LAST_NAME);
		if(isMissing(lastName)){
			lastName = "Missing last Name";
			isMissingValue = true;
		}
		
		//
		String emailAddress = request.getParameter(EMAIL_ADDRESS);
		if(isMissing(emailAddress)){
			emailAddress = "Missing Email Address";
			isMissingValue = true;
		}
		
		//
		Cookie c1 = new LongLivedCookie(FIRST_NAME, firstName);
		response.addCookie(c1);
		Cookie c2 = new LongLivedCookie(LAST_NAME, lastName);
		response.addCookie(c2);
		Cookie c3 = new LongLivedCookie(EMAIL_ADDRESS, emailAddress);
		response.addCookie(c3);
		
		//
		String formAddress = RegistrationFormServlet.class.getSimpleName();
		if(isMissingValue){
			response.sendRedirect(formAddress);
		}else{
			response.setContentType("text/html");
			//
			PrintWriter out = response.getWriter();
			//
			String title = "Thanks for Registration.";
			out.println(Constants.docType + ServletUtilities.headWithTitle(title) +
					"<body><h1>" + title + "</h1><ul><li>First Name: " + firstName +
					"</li><li>Last Name: " + lastName + "</li><li>Email-Address: " + 
					emailAddress + "</li></ul></body></html>"
					);
		}
	}
	
	private boolean isMissing(String value){
		return (null == value || value.trim().isEmpty());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private static final Logger logger = 
			Logger.getLogger(RegistrationServlet.class);

}
